<?php
namespace App\Blocks;

use App\Models\UserAddress;
use DB;
class AddressBlock{

    //我的订单列表
    public function my_address($id){
        $address = new UserAddress();
        $res = DB::table($address->getTable())
            ->select('id','name','mobile','province','city','district','address','useing')
            ->where('u_id',$id)
            ->whereNull('deleted_at')
            ->orderby('useing','desc')
            ->orderby('id','desc')
            ->get();
        return $res;
    }
    //添加收获地址
    public function my_address_save($data){
        $address = new UserAddress();
        $data['created_at'] = date('Y-m-d H:i:s',time());

        try{
            DB::beginTransaction();

            if(isset($data['useing']) && $data['useing'] == 1){
                if(DB::table($address->getTable())->where(array('u_id'=>$data['u_id']))->update(['useing' => 0]) === false){
                    return false;
                }
            }

            if(DB::table($address->getTable())->insert($data) === false){
                DB::rollBack();
                return false;
            }
            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }
    //修改收获地址
    public function my_address_update($data){
        $address = new UserAddress();
        $data['updated_at'] = date('Y-m-d H:i:s',time());

        try{
            DB::beginTransaction();

            if(isset($data['useing']) && $data['useing'] == 1){
                if(DB::table($address->getTable())->where(array('u_id'=>$data['u_id']))->update(['useing' => 0]) === false){
                    return false;
                }
            }

            if(DB::table($address->getTable())
                ->where(array('id'=>$data['id']))
                ->where(array('u_id'=>$data['u_id']))
                ->update($data) === false){
                DB::rollBack();
                return false;
            }
            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception);
            return false;
        }

    }
    //删除收获地址
    public function my_address_del($data){
        $address = new UserAddress();
        $res = DB::table($address->getTable())->where(array('id'=>$data['id']))
            ->update(['deleted_at'=>date('Y-m-d H:i:s',time())]);
        return $res;
    }

}